/*! Copyright (c) 2013 Brandon Aaron (http://brandon.aaron.sh)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Version: 3.1.9
 *
 * Requires: jQuery 1.2.2+
 */

(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node/CommonJS style for Browserify
        module.exports = factory;
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

    var toFix  = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
        toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
                    ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
        slice  = Array.prototype.slice,
        nullLowestDeltaTimeout, lowestDelta;

    if ( $.event.fixHooks ) {
        for ( var i = toFix.length; i; ) {
            $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
        }
    }

    var special = $.event.special.mousewheel = {
        version: '3.1.9',

        setup: function() {
            if ( this.addEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.addEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = handler;
            }
            // Store the line height and page height for this particular element
            $.data(this, 'mousewheel-line-height', special.getLineHeight(this));
            $.data(this, 'mousewheel-page-height', special.getPageHeight(this));
        },

        teardown: function() {
            if ( this.removeEventListener ) {
                for ( var i = toBind.length; i; ) {
                    this.removeEventListener( toBind[--i], handler, false );
                }
            } else {
                this.onmousewheel = null;
            }
        },

        getLineHeight: function(elem) {
            return parseInt($(elem)['offsetParent' in $.fn ? 'offsetParent' : 'parent']().css('fontSize'), 10);
        },

        getPageHeight: function(elem) {
            return $(elem).height();
        },

        settings: {
            adjustOldDeltas: true
        }
    };

    $.fn.extend({
        mousewheel: function(fn) {
            return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel');
        },

        unmousewheel: function(fn) {
            return this.unbind('mousewheel', fn);
        }
    });


    function handler(event) {
        var orgEvent   = event || window.event,
            args       = slice.call(arguments, 1),
            delta      = 0,
            deltaX     = 0,
            deltaY     = 0,
            absDelta   = 0;
        event = $.event.fix(orgEvent);
        event.type = 'mousewheel';

        // Old school scrollwheel delta
        if ( 'detail'      in orgEvent ) { deltaY = orgEvent.detail * -1;      }
        if ( 'wheelDelta'  in orgEvent ) { deltaY = orgEvent.wheelDelta;       }
        if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY;      }
        if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }

        // Firefox < 17 horizontal scrolling related to DOMMouseScroll event
        if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
            deltaX = deltaY * -1;
            deltaY = 0;
        }

        // Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
        delta = deltaY === 0 ? deltaX : deltaY;

        // New school wheel delta (wheel event)
        if ( 'deltaY' in orgEvent ) {
            deltaY = orgEvent.deltaY * -1;
            delta  = deltaY;
        }
        if ( 'deltaX' in orgEvent ) {
            deltaX = orgEvent.deltaX;
            if ( deltaY === 0 ) { delta  = deltaX * -1; }
        }

        // No change actually happened, no reason to go any further
        if ( deltaY === 0 && deltaX === 0 ) { return; }

        // Need to convert lines and pages to pixels if we aren't already in pixels
        // There are three delta modes:
        //   * deltaMode 0 is by pixels, nothing to do
        //   * deltaMode 1 is by lines
        //   * deltaMode 2 is by pages
        if ( orgEvent.deltaMode === 1 ) {
            var lineHeight = $.data(this, 'mousewheel-line-height');
            delta  *= lineHeight;
            deltaY *= lineHeight;
            deltaX *= lineHeight;
        } else if ( orgEvent.deltaMode === 2 ) {
            var pageHeight = $.data(this, 'mousewheel-page-height');
            delta  *= pageHeight;
            deltaY *= pageHeight;
            deltaX *= pageHeight;
        }

        // Store lowest absolute delta to normalize the delta values
        absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );

        if ( !lowestDelta || absDelta < lowestDelta ) {
            lowestDelta = absDelta;

            // Adjust older deltas if necessary
            if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
                lowestDelta /= 40;
            }
        }

        // Adjust older deltas if necessary
        if ( shouldAdjustOldDeltas(orgEvent, absDelta) ) {
            // Divide all the things by 40!
            delta  /= 40;
            deltaX /= 40;
            deltaY /= 40;
        }

        // Get a whole, normalized value for the deltas
        delta  = Math[ delta  >= 1 ? 'floor' : 'ceil' ](delta  / lowestDelta);
        deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
        deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);

        // Add information to the event object
        event.deltaX = deltaX;
        event.deltaY = deltaY;
        event.deltaFactor = lowestDelta;
        // Go ahead and set deltaMode to 0 since we converted to pixels
        // Although this is a little odd since we overwrite the deltaX/Y
        // properties with normalized deltas.
        event.deltaMode = 0;

        // Add event and delta to the front of the arguments
        args.unshift(event, delta, deltaX, deltaY);

        // Clearout lowestDelta after sometime to better
        // handle multiple device types that give different
        // a different lowestDelta
        // Ex: trackpad = 3 and mouse wheel = 120
        if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
        nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);

        return ($.event.dispatch || $.event.handle).apply(this, args);
    }

    function nullLowestDelta() {
        lowestDelta = null;
    }

    function shouldAdjustOldDeltas(orgEvent, absDelta) {
        // If this is an older event and the delta is divisable by 120,
        // then we are assuming that the browser is treating this as an
        // older mouse wheel event and that we should divide the deltas
        // by 40 to try and get a more usable deltaFactor.
        // Side note, this actually impacts the reported scroll distance
        // in older browsers and can cause scrolling to be slower than native.
        // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false.
        return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0;
    }

}));

/**
 * [{
 *      keyname : "第一天",
 *      time : "2000-00-00 00:00:00"
 *      subcontent : [{
 *          description : "这一天心情很哈皮",
 *          details : [{
 *              image: "......",
 *              text : "......",
 *              time : '',
 *              favourte : 12,
 *              is_favou : false
 *          }]
 *      }]
 * }]
*/
(function(w){
    $ = w.jQuery
    function Work(){}
    Work.prototype = {
        control_page : null,
        outerWidth : 1,
        key_node : [],
        page_control : null,
        init : function (div,json,opt){
            this._createStruct(div)
            this._create_key_box(div,json)
            if(opt.pagecontrol){
                this.page_control = this.create_page_control(div)
                if(opt.point_click){
                    this.addEventForPagePoint(opt.move ? opt.move : false)
                }
            }
        },
        create_page_control:function(dom){
            var target = $('<div class="kd-page-control"></div>')
            var ul = $('<ul></ul>')
            target.append(ul)
            dom.append(target)
            $.each(this.key_node,function(i,v){
                var mainP = $('<li></li>').addClass('kd-main-point')
                if(i == 0){
                    mainP.addClass('active')
                }
                ul.append(mainP)
                $.each(v.sub_node,function(ind){
                    var subP = $('<li></li>').addClass('kd-sub-point')
                    mainP.after(subP)
                })
            })
            return target
        },
        addEventForPagePoint:function(callback){
            var control = this.page_control
            var self = this
            control.find('li').css({
                cursor : 'pointer'
            })
            control.on('click','li',function(){
                var index = control.find('li').index(this);
                var c = 0
                var ele = null
                var offsetLeft = 0
                for(var i =0;i<self.key_node.length;i++){
                    if(c != index){
                        var me = self.key_node[i]
                        c++
                        for(var a in me['sub_node']){
                            if(c != index){
                                c++
                            }else{
                                ele = me['sub_node'][a]
                                offsetLeft = ele['dom'].position()['left']
                                break
                            }
                        }
                        if(ele){
                            break
                        }
                    }else{
                        ele = self.key_node[i]
                        offsetLeft = ele['dom'].position()['left']
                        break
                    }
                }
                if(!self.control_page.is(":animated")){
                    self.control_page.animate({
                        left : offsetLeft*-1
                    },'slow','swing',function(){
                        $('.kd-page-control').find('li').removeClass('active')
                        var x = index + 1
                        $('.kd-page-control').find('li:nth-child('+x+')').addClass('active')
                        if(callback){
                            callback({
                                type : 'pagecontrol',
                                dectence : offsetLeft,
                                current : ele
                            })
                        }
                    })
                }
            })
        },
        _createStruct : function (div){
            this.control_page = $('<div class="kd-scroll-box" id="kd-scroll-box"></div>').css('width','9999px')
            var c = $('<div class="kd-scroll-container"></div>')
            c.append(this.control_page)
            div.append(c)
        },
        _create_key_box:function(div,json){
            var self = this
            var totlaCou = 0
            $.each(json,function(index,value){
                var height = div.height()-70
                var proportion = 154/89
                var width = height/proportion
                var mainPage = $('<div class="kd-scroll-node"><div class="main-page"><div class="title">'+value.keyname+'</div><div class="day-date">'+value.time+'</div></div></div>').css({width:width})
                var target = $("<div class='kd-scroll-key-box'></div>")
                target.append(mainPage)
                self.control_page.append(target)

                //保存关键节点
                self.key_node.push({
                    dom: target,
                    json_value : value,
                    sub_node : []
                })

                self.outerWidth += $(target).outerWidth(true)
                self.control_page.css({
                    width : self.outerWidth
                })
                totlaCou ++
                $.each(value.subcontent,function(i,v){
                    if(v.description){
                        totlaCou ++
                        var target = $("<div class='kd-scroll-key-box'></div>")
                        var subPage = $('<div class="kd-scroll-node"><div class="sub-page"><div class="title">'+v.description+'</div></div></div>').css({width:width})
                        target.append(subPage)
                        self.control_page.append(target)

                        self.outerWidth += $(target).outerWidth(true)
                        self.control_page.css({
                            width : self.outerWidth
                        })
                        self.key_node[index]['sub_node'].push({
                            dom:target,
                            json_value : v,
                        })
                    }
                    self.sort_image(v.details,function(single,double){
                        $.each(single,function(i,image){
                            self.render_single(target,height+25,image)
                        })
                        self.render_double(target,height,double)
                        //计算总宽度
                        totlaCou += single.length
                        totlaCou += double.length/2
                    })
                })
            })
        },
        sort_image:function(imgs,complete){
            var self = this
            var single = []
            var double = []
            $.each(imgs,function(i,v){
                var temp = new Image()
                temp.src = v.image
                
                temp.onload = function (){
                    v.width = temp.width
                    v.height = temp.height
                    if(temp.width >= 1100 && temp.height >= 1100){
                        v.dom = temp
                        single.push(v)
                    }else if(temp.width/temp.height >1){
                        v.dom = temp
                        double.push(v)
                    }else{
                        v.dom = temp
                        single.push(v)
                    }
                    if(complete && single.length + double.length == imgs.length){
                        if(double.length % 2 != 0){
                            single.push(double.pop())
                        }
                        complete(single,double)
                    }
                }
            })
        },
        calculate_img_size:function(img,target,type){
            var w = img.width
            var h = img.height
            if(type == 'width'){
                return Math.ceil(w / h * target) 
            }
            return Math.ceil(h / w * target) 
        },
        render_single : function(lastEle,height,img){
            var self = this
            var w = this.calculate_img_size(img,height,'width')
            var target = $("<div class='kd-scroll-key-box'></div>")
            var curEle = $('<div class="kd-scroll-node"></div>').css({
                width : w
            })
            img.dom.width = w
            if(img.text){
                curEle.append($("<div class='kd-temp1'></div>").append($('<a href="'+img.dom.src+'" data-fancybox="img" data-caption="'+img.text+'"></a>').append(img.dom)).append("<div class='text-shadow'>"+img.text+"</div>"))
            }
            target.append(curEle)
            lastEle.after(target)
            self.outerWidth += $(target).outerWidth(true)
            self.control_page.css({
                width : self.outerWidth
            })
        },
        render_double:function(lastEle,height,imgs){
            
            var self = this
            var haf_hei = height/2 - 10
            $.each(imgs,function(i,v){
                if(i%2==1){
                    var v1 = imgs[i - 1]
                    var v1_width = self.calculate_img_size(v1,haf_hei,'width')
                    var v2 = imgs[i]
                    var v2_width = self.calculate_img_size(v2,haf_hei,'width')
                    var last_width = v1_width > v2_width ? v2_width : v1_width
                    var target = $("<div class='kd-scroll-key-box'></div>")
                    var curEle = $('<div class="kd-scroll-node"></div>').css({
                        width : last_width
                    })
                    v1.dom.width = last_width
                    v2.dom.width = last_width

                    curEle.append($("<div class='kd-temp2'></div>").append($('<div class="pic1"></div>').append($('<div class="img"></div>').append($("<a href='"+v1.dom.src+"' data-fancybox='img' data-caption='"+v1.text+"'></a>").append(v1.dom)).append("<div class='text-shadow'>"+v1.text+"</div>")))
                                                                    .append($('<div class="pic2"></div>').append($('<div class="img"></div>').append($("<a href='"+v2.dom.src+"' data-fancybox='img' data-caption='"+v2.text+"'></a>").append(v2.dom)).append("<div class='text-shadow'>"+v2.text+"</div>"))))
                    
                    target.append(curEle)
                    lastEle.after(target)
                    self.outerWidth += $(target).outerWidth(true)
                    self.control_page.css({
                        width : self.outerWidth
                    })
                }
            })
        }
    }
    $.fn.extend({
        workplace : function (opt){
            var json = opt.data
            this.css({
                position : 'relative',
            })
            var work = new Work()
            opt.pagecontrol = opt.pagecontrol ? opt.pagecontrol : false
            opt.point_click = opt.point_click ? opt.point_click : false
            work.init(this,json,opt)
            var self = this
            this.mousewheel(function(event,delta){
                delta = event.deltaFactor * delta
                if($('#kd-scroll-box').position().left <= 0 && $('#kd-scroll-box').position().left >= -1*$('#kd-scroll-box').outerWidth(true)+self.width() ){
                    var dectence = $('#kd-scroll-box').position().left + delta
                    if(dectence>=0){
                        dectence = 0
                    }
                    if(dectence <= -1*$('#kd-scroll-box').outerWidth(true)+self.width()){
                        dectence = -1*$('#kd-scroll-box').outerWidth(true)+self.width()
                    }
                    $('#kd-scroll-box').css('left', dectence + 'px')
                    if(opt.move){
                        var inModel = null
                        var subModel = null
                        var key_node = work.key_node
                        if(!key_node[0]['offsetLeft']){
                            $.each(key_node,function(index,ele){
                                ele.offsetLeft = ele.dom.position().left
                                $.each(ele.sub_node,function(i,v){
                                    v.offsetLeft = v.dom.position().left
                                })
                            })
                        }
                        var temp = {offsetLeft : Math.abs(dectence)}
                        var tempArr = []
                        var tempSub = []
                        for(var a in key_node){
                            tempArr.push(key_node[a])
                            $.each(key_node[a]['sub_node'],function(i,v){
                                tempSub.push(v)
                            })
                        }
                        tempArr.push(temp)
                        tempSub.push(temp)
                        var tempSort = tempArr.sort(function(a,b){
                            return a.offsetLeft>b.offsetLeft?1:-1
                        })
                        var index = tempSort.indexOf(temp)

                        var subSort = tempSub.sort(function(a,b){
                            return a.offsetLeft>b.offsetLeft?1:-1
                        })
                        var subIndex = subSort.indexOf(temp)
                        
                        index--
                        if(index < 0){
                            index = 0
                        }

                        subIndex--
                        if(subIndex<0){
                            subIndex = 0
                        }
                        inModel = tempArr[index]
                        subModel = tempSub[subIndex]
                        //修改pagecontrol亮点
                        var pointArr = []
                        for (var key in key_node) {
                            pointArr.push(key_node[key])
                            if (key_node[key].sub_node) {
                                for (var key1 in key_node[key].sub_node) {
                                    pointArr.push(key_node[key]['sub_node'][key1])
                                }
                            }
                        }
                        pointArr.push(temp)
                        var pointSort = pointArr.sort(function(a,b){
                            return a.offsetLeft>b.offsetLeft?1:-1
                        })
                        var pointIndex = pointSort.indexOf(temp)
                        pointIndex--
                        if(pointIndex < 0){
                            pointIndex = 0
                        }
                        
                        opt.move({
                            type:'scroll',
                            dectence:dectence,
                            mainModule : inModel.dom,
                            subModule : subModel.dom,
                            current:pointArr[pointIndex]
                        })
                        if(opt.pagecontrol){
                            $('.kd-page-control').find('li').removeClass('active')
                            var x = pointIndex + 1
                            $('.kd-page-control').find('li:nth-child('+x+')').addClass('active')
                        }
                    }
                }
                event.stopPropagation();
                event.preventDefault();
            })
        }
    });
})(window)

